package com.cnt.controller;


import com.cnt.entity.Persons;
import com.cnt.service.PersonService;
import com.cnt.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.util.List;

@RestController
@RequestMapping("/api/persons")
public class PersonsController {
    @Autowired
    private PersonService personService;

    @GetMapping("/getPersons")
    public ResultVo<List<Persons>> getPersons(@RequestParam(name = "userId") Integer userId) {
        return personService.getPersons(userId);
    }
    @GetMapping("/getPerson")
    public ResultVo<Persons> getPerson(@RequestParam(name = "personsId") Integer personsId) {
        return personService.getPerson(personsId);
    }
    @PostMapping("/addPerson")
    public ResultVo<Persons> addPerson(@RequestBody Persons person) {
        return personService.addPerson(person);
    }

    @PutMapping("/updatePersons")
    public ResultVo<Persons> updatePersons(@RequestBody Persons person){
        return personService.updatePersons(person);
    }

    @PostMapping("/deletePersons")
    public ResultVo<Persons> deletePersons(@RequestBody Persons person){
        return personService.deletePersons(person.getPersonId());
    }

    @PostMapping("/upload")
    public ResultVo<String> upload(@RequestParam("file") MultipartFile file,
                                   @RequestParam(value="personId", required=false) Integer personId) {
        return personService.upload(file,personId);
    }

    @GetMapping(value = "/download", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<byte[]> download(@RequestParam(value="personId", required=false) Integer personId) {
        try (BufferedInputStream bis = new BufferedInputStream(personService.download(personId), 4096)) {
            byte[] data = new byte[bis.available()];
            bis.read(data);
            if (data.length == 0) {
                return ResponseEntity.status(500).body(null);
            }
            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment; filename=personFile.pdf")
                    .body(data);
        } catch (Exception e) {
            // 处理文件下载失败的情况
            return ResponseEntity.status(500).body(null);
        }
    }

}

